from universal.common_header import *
from universal.common_header_widget import *
from functools import partial
from mylibs.lib import struct, newAction, newIcon, addActions, fmtShortcut, generateColorByText
from universal.translate.CHINESE import *
from universal.custom.ini_file import *
from mylibs.zoomWidget import ZoomWidget
from Module.xRayDetection.xray.logs import Logger

class action_tool(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.mainwindow = parent

    def GetAction(self):
        action = partial(newAction, self)
        # ---------------------X-ray定制-----------------------
        # Over_kill = action(OVER_KILL, lambda: self.mainwindow.xrayClass_func('过杀'), '1', 'icons/overkill', OVER_KILL_DETAIL, enabled=True)
        PosetiveEscape_kill = action(POSE_ESCAPE_KILL, lambda: self.mainwindow.xrayClass_func('正极翻'), '3', 'icons/poseEscape',
                                     POSE_ESCAPE_KILL_DETAIL, enabled=True)
        NegativeEscape_kill = action(ESCA_ESCAPE_KILL, lambda: self.mainwindow.xrayClass_func('负极翻'), '4', 'icons/negaEscape',
                                     ESCA_ESCAPE_KILL_DETAIL, enabled=True)
        DeleteEveryKill = action(UNDO, lambda: self.mainwindow.xrayClass_func('撤销标签类别'), 'Ctrl+Z', 'icons/undo1', UNDO_DETAIL, enabled=True)
        # Escape_kill = action('漏杀', lambda: self.mainwindow.xrayClass_func('漏杀'), '2', 'icons/escape', '漏杀', enabled=True)
        xray_class1 = action('机损', lambda: self.mainwindow.xrayClass_func('机损'), '5', 'icons/broken', '机损', enabled=True)
        xray_class2 = action('超限', lambda: self.mainwindow.xrayClass_func('超限'),'6', 'icons/overLimit', '超限', enabled=True)
        xray_class3 = action('错层', lambda: self.mainwindow.xrayClass_func('错层'), '7', 'icons/cuo_ceng', '错层', enabled=True)
        xray_class4 = action('极片偏移', lambda: self.mainwindow.xrayClass_func('极片偏移'), '8', 'icons/offset', '极片偏移', enabled=True)
        xray_class5 = action('局部偏移', lambda: self.mainwindow.xrayClass_func('局部偏移'), '9', 'icons/offsetPart', '局部偏移', enabled=True)
        xray_class6 = action('整体偏移', lambda: self.mainwindow.xrayClass_func('整体偏移'), '0', 'icons/offsetAll', '整体偏移', enabled=True)
        
        Over_kill = action('OK', lambda: self.mainwindow.xrayClass_func('OK'), '1', 'icons/overkill', 'OK', enabled=True)
        Escape_kill = action('NG', lambda: self.mainwindow.xrayClass_func('NG'), '2', 'icons/escape', 'NG', enabled=True)
        

        openNextImg = action(NEXT_IMAGE, self.mainwindow.openNextImg,  'd', 'icons/next', NEXT_IMAGE_DETAIL)
        openPrevImg = action(PREV_IMAGE, self.mainwindow.openPrevImg, 'a', 'icons/prev', PREV_IMAGE_DETAIL)
        save = action(SAVE, self.mainwindow.saveFile_, 'Ctrl+S', 'icons/save', SAVE_DETAIL, enabled=False)  #######save##
        save_format = action(PASCALVOC, self.mainwindow.change_format, 'Ctrl+P', 'icons/format_voc', PASCALVOC_DETAIL,
                             enabled=True)
        color1 = action(BOX_LINE_COLOR, self.mainwindow.chooseColor1, 'Ctrl+L', 'icons/color_line', BOX_LINE_COLOR_DETAIL)
        create = action(CREATE_RECT_BOX, lambda: self.mainwindow.createShape(0), 'w', 'icons/new', DRAW_A_NEW_BOX, enabled=False)
        create_poly = action(CREATE_POLY_BOX, lambda: self.mainwindow.createShape(1), 'q', 'icons/polygon', DRAW_A_NEW_BOX, enabled=False)
        self.delete = action(DELETE_RECT_BOX, self.mainwindow.deleteSelectedShape, 'Delete', 'icons/delete', DELETE, enabled=False)
        self.edit = action(EDIT_LABEL, self.mainwindow.labelList.editLabel, '', 'icons/edit', EDIT_LABEL_DETAIL, enabled=False)
        self.Add_ = action('add', self.add_label, 'Add', 'icons/done', 'Add', enabled=True)
        self.Delete_ = action('delete', self.DeleteItem, 'delete', 'icons/delete', 'delete', enabled=True)
        self.edit222 = action(EDIT_LABEL, self.editLabel222, 'Class_edit', 'icons/edit', EDIT_LABEL_DETAIL, enabled=True)  #
        copy = action(DUPLICATE_RECT_BOX, self.mainwindow.copySelectedShape, 'Ctrl+D', 'icons/copy', DUPLICATE_RECT_BOX_DETAIL, enabled=False)
        help = action(TUTORIAl, self.mainwindow.showTutorialDialog, None, 'icons/help', TUTORIAl_DETAIL)
        showInfo = action(INFORMATION, self.mainwindow.showInfoDialog, None, 'icons/help', INFORMATION_DETAIL)
        No_defect = action('No_defect', self.mainwindow.NoDefect, 'No_Defect', 'icons/done', 'No_defect', enabled=True)

        self.zoomWidget = ZoomWidget()
        self.zoomWidget.setWhatsThis(ZOOM_WIDGET_SET_WHAT_THIS % (fmtShortcut("Ctrl+[-+]"), fmtShortcut("Ctrl+Wheel")))
        self.zoomWidget.setEnabled(False)
        zoomIn = action(ZOOM_IN, partial(self.mainwindow.addZoom, 10), 'Ctrl++', 'icons/zoom-in', ZOOM_IN_DETAIL, enabled=False)
        zoomOut = action(ZOOM_OUT, partial(self.mainwindow.addZoom, -10), 'Ctrl+-', 'icons/zoom-out', ZOOM_OUT_DETAIL,enabled=False)
        zoomOrg = action(ZOOM_ORG, partial(self.mainwindow.setZoom, 100), 'Ctrl+=', 'icons/zoom', ZOOM_ORG_DETAIL, enabled=False)
        fitWindow = action(ZOOM_WINDOW, self.mainwindow.setFitWindow, 'Ctrl+F', 'icons/fit-window', ZOOM_WINDOW_DETAIL,checkable=True, enabled=False)

        newProject = action(NEW_PR0JECT, self.newProject_toolbar, 'Ctrl+N', 'icons/open', NEW_PR0JECT_DETAIL,enabled=True)
        openMyProject = action(OPEN_PR0JECT, self.mainwindow.openMyProject2, 'Ctrl+O', 'icons/Opendir', OPEN_PR0JECT_DETAIL,enabled=True)
        saveProject = action(SAVE_PROJECT, self.mainwindow.saveSettings, 'Ctrl+S', 'icons/save', SAVE_PROJECT_DETAIL,enabled=True)  # 注释

        Contact_us = action('&Contact us', self.mainwindow.contactus, 'Ctrl+S', 'icons/contact1', 'Contact Us', enabled=True)
        exportProject = action('&Export Report', self.mainwindow.exportProjectAs, '', 'None', 'Switch the project',enabled=True)
        exportResultPic = action(EXPORT_PR0JECT, self.exportResultPic_, 'None', 'None', EXPORT_PR0JECT_DETAIL)

        self.Industry_model = action('打开工厂模式', self.mainwindow.IndustryModel, 'None', 'None', "工厂模式")
        close_Industry_model = action('关闭工厂模式', self.Close_IndustryModel, 'None', 'None', "工厂模式")
        line_Thickness = action('调整线条粗细', self.line_thick, 'None', 'None', "调整线条粗细")

        self.labelpageAction = action('Label', self.displayLabelPage, None, 'icons/label_s', 'go to label page',enabled=True)
        self.trainpageAction = action('Train', self.mainwindow.displayTrainPage, None, 'icons/train', 'go to train page',enabled=True)
        self.testpageAction = action('Predict', self.mainwindow.displayTestPage, None, 'icons/detect', 'go to test page',enabled=True)
        self.FTPpageAction = action('FTP', self.mainwindow.displayFtpPage, None, 'icons/Ftp', 'go to ftp page', enabled=True)
        self.D3DpageAction = action('3D', self.mainwindow.display3dPage, None, 'icons/3D', 'go to 3d page', enabled=True)
        self.ClassicalAction = action('OpenCV', self.mainwindow.displayClassical, None, 'icons/view_2d.png', 'go to classical page', enabled=True)

        zoomActions = (self.zoomWidget, zoomIn, zoomOut, zoomOrg, fitWindow)
        if ODModule_config.read_value('Industry', 'page') == "1":
            Industry_model_select = QMenu('工厂模式')
            Industry_model_select.addActions([self.Industry_model, close_Industry_model])
            Tuple = (exportResultPic, line_Thickness, color1, Industry_model_select)
        else:
            Tuple = (exportResultPic, line_Thickness, color1)

            # Store actions for further handling.
        self.actions = struct(save=save, save_format=save_format, lineColor=color1,
                              create=create,create_poly=create_poly, No_defect=No_defect, delete=self.delete, edit=self.edit, copy=copy,
                              # ---------------------------------Xray定制-----------------------------------
                              Over_kill=Over_kill, Escape_kill=Escape_kill, PosetiveEscape_kill=PosetiveEscape_kill,
                              NegativeEscape_kill=NegativeEscape_kill, xray_class1=xray_class1, xray_class2=xray_class2,
                              xray_class3=xray_class3, xray_class4=xray_class4, xray_class5=xray_class5,
                              xray_class6=xray_class6,
                              
                            #   Over_kill=Over_kill, Escape_kill=Escape_kill,
                              
                              # ---------------------------------------------------------------------------
                              fitWindow=fitWindow, zoomActions=zoomActions, beginner=(), advanced=(),
                              editMenu=Tuple, beginnerContext=(create, create_poly,self.edit, copy, self.delete),
                              advancedContext=(self.edit, copy, self.delete))

        self.actions.beginner = (openNextImg, openPrevImg, save, create, create_poly,self.delete, copy, fitWindow)
        # --------------------------xray定制-------------------------
        # self.actions.Xray = (
        #     Over_kill, Escape_kill, None, PosetiveEscape_kill, NegativeEscape_kill, xray_class1, None, xray_class2,
        #     xray_class3, xray_class4, xray_class5, xray_class6, None, DeleteEveryKill)
        
        self.actions.Xray = (Over_kill, Escape_kill)

        # self.dock = QDockWidget(self)
        labels = self.mainwindow.dock.toggleViewAction()
        labels.setText(SHOW_HIDE_LABEL)
        labels.setShortcut('Ctrl+Shift+L')

        if ODModule_config.read_value('Label_Tools', 'page') == "1": #判断是否要打开菜单栏
            self.menus = struct(
                file=self.add(FILE),
                edit=self.add(EDIT),
                view=self.add(VIEW),
                help=self.add(HELP),
                recentFiles=QMenu(OPEN_RECENT))  #
            if ODModule_config.read_value('ExportReport', 'Open') == "1":
                addActions(self.menus.file, (newProject, saveProject, exportProject))
            else:
                addActions(self.menus.file, (newProject, saveProject))  # 导报告

            addActions(self.menus.help, (help, showInfo))
            addActions(self.menus.view, (self.mainwindow.autoSaving, self.mainwindow.singleClassMode, labels))
            self.menus.file.aboutToShow.connect(lambda: self.updateFileMenu())
            self.updateFileMenu()#
            self.populateModeActions()

        addActions(self.mainwindow.canvas.menus[0], self.actions.beginnerContext)
        addActions(self.mainwindow.canvas.menus[1], (action(COPY_HERE, self.mainwindow.copyShape),action(MOVE_HERE, self.mainwindow.moveShape)))


        return self.labelpageAction,self.trainpageAction,self.testpageAction,self.FTPpageAction, \
        self.Industry_model,self.D3DpageAction,self.ClassicalAction,self.actions,self.edit, self.delete


    def newProject_toolbar(self):
        if self.mainwindow.dirty == True:
            self.mainwindow.saveFile_()
        self.mainwindow.saveSettings()
        self.mainwindow.mainWindow_.show()


    def line_thick(self):
        self.mainwindow.mainWindow_slider.canvas = self.mainwindow.canvas
        self.mainwindow.mainWindow_slider.show()  #


    def add(self, title, actions=None):
        menu = self.mainwindow.menuBar().addMenu(title)

        if actions:
            addActions(menu, actions)
        return menu


    def updateFileMenu(self):
        currFilePath = self.mainwindow.filePath
        def exists(filename):
            return os.path.exists(filename)

        menu = self.menus.recentFiles
        menu.clear()
        files = [f for f in self.mainwindow.recentFiles if f !=
                 currFilePath and exists(f)]
        for i, f in enumerate(files):
            icon = newIcon('labels')
            action = QAction(
                icon, '&%d %s' % (i + 1, QFileInfo(f).fileName()), self.mainwindow)
            action.triggered.connect(partial(self.mainwindow.loadRecent, f))
            menu.addAction(action)


    def populateModeActions(self):
        tool, menu = self.actions.beginner, self.actions.beginnerContext
        self.mainwindow.canvas.menus[0].clear()
        addActions(self.mainwindow.canvas.menus[0], menu)
        self.menus.edit.clear()
        addActions(self.menus.edit, self.actions.editMenu)  #

    def exportResultPic_(self):
        self.mainwindow.TextBrowser.clear()
        self.thread_train = threading.Thread(target=self.exportResultPic2_, args='')
        self.thread_train.daemon = True
        self.thread_train.start()

    def exportResultPic2_(self):
        try:
            projdir = os.path.dirname(self.mainwindow.xmlFilePath)
            resultDir = os.path.join(projdir, 'resultDir')  # 2
            if not os.path.exists(resultDir):
                os.makedirs(resultDir)
            name_ = os.listdir(self.mainwindow.labelImgsPath)
            name_ = self.mainwindow.mImgList #图像列表

            for jpgname in name_:
                NO_houzhui = os.path.splitext(jpgname)[0] #没有后缀的路径
                xmlfile = NO_houzhui + '.xml'
                if os.path.exists(xmlfile):
                    TextBrowserNews(self.mainwindow.TextBrowser, jpgname)
                    drawBox(jpgname, resultDir, xmlfile)

        except Exception as e:
            self.mainwindow.logger.log(Logger.ERROR, str(e), exception=True)
            TextBrowserNews(self.mainwindow.TextBrowser, news=str(e))

    def editLabel222(self):
        try:
            if not self.mainwindow.canvas.editing():
                return
            item = self.mainwindow.labelList.currentItem()
            if item == None:
                return
            else:
                text = self.mainwindow.labelDialog.popUp(item.text())  ####
                if text is not None:
                    item.setText(text)
                    item.setBackground(generateColorByText(text))
                    self.mainwindow.setDirty()
                self.finishClassesEdit()
        except Exception as e:
            self.logger.log(Logger.ERROR, str(e), exception=True)

    def add_label(self):
        item = self.mainwindow.labelList.currentItem()
        text = self.mainwindow.labelDialog.popUp(text=self.mainwindow.prevLabelText)
        classes = []
        if text is not None:
            for i in range(self.mainwindow.labelList.count()):
                classes.append(self.mainwindow.labelList.item(i).text())
            classes.insert(0, text)

        item = QListWidgetItem(text)
        self.mainwindow.labelList.addItem(item)
        self.finishClassesEdit()


    def finishClassesEdit(self):
        self.classesList = []
        for i in range(self.mainwindow.labelList.count()):
            self.classesList.append(self.mainwindow.labelList.item(i).text())

    def DeleteItem(self):
        self.mainwindow.labelList.takeItem(self.mainwindow.labelList.currentRow())
        self.finishClassesEdit()

    def SHOW_bar(self):
        self.mainwindow.toolsdaohang.show()
        if self.mainwindow.labelFlag == False:
            self.mainwindow.label()
            self.mainwindow.labelFlag = True

    def Close_IndustryModel(self):  ####
        self.mainwindow.IndustryWidget.exitIndustryModel()
        self.mainwindow.SetTruePage(self.labelpageAction,self.mainwindow.labelDockWidget,False)
        if self.mainwindow.labelFlag == False:
            self.SHOW_bar()
        self.mainwindow.importDirImages(self.mainwindow.labelImgsPath)

    def displayLabelPage(self):  #
        self.mainwindow.SetTruePage(self.labelpageAction,self.mainwindow.labelDockWidget,False)
        self.SHOW_bar()

